package musicstore.web.controller;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import musicstore.biz.AlbumBiz;
import musicstore.biz.GenreBiz;
import musicstore.biz.UserBiz;
import musicstore.entity.User;

@Controller
public class HomeController {
	@Autowired
	private AlbumBiz albumbiz;
	@Autowired
	private GenreBiz genrebiz;
	@Autowired
	private UserBiz userbiz;

	@RequestMapping("/index")
	public String index(Integer genreId, String title, Integer pageNum, Model model) {
		genreId = genreId == null ? 0 : genreId;
		pageNum = pageNum == null ? 1 : pageNum;
		int pageSize = 9;
		int rows = albumbiz.getRows(genreId, title);
		int totalPages = rows % pageSize == 0 ? rows / pageSize : rows / pageSize + 1;
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pagetotal", totalPages);
		model.addAttribute("categories", genrebiz.getAll());
		model.addAttribute("albumlist", albumbiz.fetchAlbumspage(genreId, title, pageNum, pageSize));
		return "index";
	}

	@RequestMapping(value = { "/login" }, method = RequestMethod.GET)
	public String login(Model model) {
		model.addAttribute("categories", genrebiz.getAll());
		return "login";
	}

	@RequestMapping(value = { "/login" }, method = RequestMethod.POST)
	public String login(HttpSession session, String username, String password, Model model) {
		User user = userbiz.checkLogin(username,password);
		if (user != null) {
			session.setAttribute("user", user);
			session.setAttribute("username", user.getName());
			return "redirect:/index";
		} else {
			model.addAttribute("message", "账户密码有误！");
			return "login";
		}
	}
	@RequestMapping("/sidebar")
	public String sidebar(Map<String,Object> model){
		model.put("categories", genrebiz.getAll());
		return "sidebar";
	}
	@RequestMapping("/register")
	public String register(){

		return "register";
	}
}
